package com.have.blog.web.service.impl;

import com.github.pagehelper.PageHelper;
import com.have.blog.base.enums.BlogStatus;
import com.have.blog.model.mapper.BlogSubjectItemMapper;
import com.have.blog.model.models.BlogSubjectItem;
import com.have.blog.model.models.BlogSubjectItemExample;
import com.have.blog.utils.MyBeanUtils;
import com.have.blog.web.dto.BlogDto;
import com.have.blog.web.dto.BlogSubjectItemDto;
import com.have.blog.web.service.BlogSubjectItemService;
import com.have.blog.web.service.WebBlogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

@Service
@SuppressWarnings("all")
public class BlogSubjectItemServiceImpl  implements BlogSubjectItemService {
    @Autowired
    private BlogSubjectItemMapper subjectItemMapper;
    @Autowired
    private WebBlogService blogService;

    @Override
    public List<BlogSubjectItemDto> getListBySubjectUid(Integer subjectUid, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        BlogSubjectItemExample example = new BlogSubjectItemExample();
        example.createCriteria()
                .andStatusEqualTo(BlogStatus.ENABLE.getStatus())
                .andBlogSubjectUidEqualTo(subjectUid);
        example.setOrderByClause("sort desc");
        List<BlogSubjectItem> subjectItemList = subjectItemMapper.selectByExample(example);
        List<Integer> blogUids = new ArrayList<>();
        for (BlogSubjectItem item : subjectItemList) {
            blogUids.add(item.getBlogUid());
        }
        if (CollectionUtils.isEmpty(blogUids)) {
            return MyBeanUtils.copyListProperties(subjectItemList, BlogSubjectItemDto::new);
        }
        List<BlogDto> blogList = blogService.getBlogByUids(blogUids);
        List<BlogSubjectItemDto> resultList = new ArrayList<>();
        for (BlogDto blogDto : blogList) {
            resultList.add(BlogSubjectItemDto
                    .builder()
                    .subjectUid(subjectUid)
                    .blog(blogDto)
                    .build());
        }
        return resultList;
    }
}
